package com.fulu.game.bi.common.util.encrypt;

import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.RandomUtil;
import com.fulu.game.bi.common.Constants;
import lombok.Data;
import lombok.ToString;
import lombok.extern.slf4j.Slf4j;

import java.security.MessageDigest;

@Slf4j
public class EncryptUtils {
    /**
     * 注册时调用，此方法用于通过原生密码生成随机盐和加密密码
     */
    public static Password PiecesEncode(String plainPassword) {
        String random = RandomUtil.randomString(32);
        return PiecesEncode(plainPassword, random);
    }

    /**
     * 登录时调用，此方法用于通过原生密码和盐生成加密密码
     * @return Password class which contains salted password and salt.
     */
    public static Password PiecesEncode(String plainPassword, String salt, String... encodes) {
        String encode = ArrayUtil.isEmpty(encodes) ? Constants.DEFAULT_CHARSET : encodes[0];
        plainPassword = salt + plainPassword;
        Password p = new Password();
        p.setPlainPassword(plainPassword);
        p.setSalt(salt);
        p.setPassword(EncryptUtils.getSHA1(plainPassword, encode));
        return p;
    }

    public static String getSHA1(String str, String encode) {
        return encode(str, "SHA-1", encode);
    }

    private static String encode(String str, String type, String encode) {
        try {
            MessageDigest alga = MessageDigest.getInstance(type);
            alga.update(str.getBytes(encode));
            byte[] digesta = alga.digest();
            return byte2hex(digesta);
        } catch (Exception e) {
            log.warn("加密发生异常", e);
            return "";
        }
    }

    public static String byte2hex(byte[] b) {
        String hs = "";
        String stmp = "";
        for (int n = 0; n < b.length; n++) {
            stmp = (Integer.toHexString(b[n] & 0XFF));
            if (stmp.length() == 1)
                hs = hs + "0" + stmp;
            else
                hs = hs + stmp;
        }
        return hs.toUpperCase();
    }
    @Data
    @ToString
    public static class Password {
        private String password;
        private String salt;
        private String plainPassword;
    }
}
